import React, { useState } from "react";
import { Node, Cell } from "@antv/x6";
import { Tooltip } from "antd";
import { PlusCircleOutlined } from "@ant-design/icons";
import { NodeType, NODE_TYPE_LOGO } from "./types";
import { createNode, createEdge, getDownstreamNodePosition } from "./utils";
import NodeTypeSelector from "./NodeTypeSelector";

/**
 * @file CustomNode.tsx
 * @description 自定义节点组件，用于显示和操作流程图中的节点
 */

/**
 * 自定义节点组件
 * 显示节点信息、处理节点交互、支持添加下游节点
 */
const CustomNode: React.FC<{ node: Node }> = ({ node }) => {
  // 控制+号显示的状态
  const [showPlus, setShowPlus] = useState(false);
  // 节点选择下拉是否显示
  const [plusActionSelected, setPlusActionSelected] = useState(false);
  // 菜单位置
  const [menuPosition, setMenuPosition] = useState({ x: 0, y: 0 });
  // 获取节点数据
  const data = node.getData();

  /**
   * 创建下游的节点和边
   * @param type 节点类型
   */
  const createDownstream = (type: string) => {
    const { graph } = node.model || {};
    if (graph) {
      // 获取下游节点的初始位置信息
      const position = getDownstreamNodePosition(node, graph);
      // 创建下游节点
      const newNode = createNode(type, graph, position);
      // 创建该节点出发到下游节点的边
      createEdge(node.id, newNode.id, graph);
    }
  };

  /**
   * 处理节点类型选择
   * @param nodeType 节点类型
   */
  const handleNodeTypeSelect = (nodeType: string) => {
    createDownstream(nodeType);
    setPlusActionSelected(false);
  };

  /**
   * 点击加号按钮，设置菜单位置并显示菜单
   * @param e 点击事件
   */
  const handlePlusClick = (e: React.MouseEvent) => {
    const rect = e.currentTarget.getBoundingClientRect();
    setMenuPosition({
      x: rect.left,
      y: rect.bottom,
    });
    setPlusActionSelected(true);
  };

  /**
   * 更新连接桩状态
   * @param visible 是否显示连接桩
   */
  const updatePortsVisibility = (visible: boolean) => {
    const ports = node.getPorts() || [];
    ports.forEach((port) => {
      node.setPortProp(port.id as string, "attrs/circle", {
        fill: visible ? "#fff" : "transparent",
        stroke: visible ? "#85A5FF" : "transparent",
      });
    });
  };

  /**
   * 鼠标进入矩形主区域的时候显示连接桩和加号
   */
  const handleMainMouseEnter = () => {
    updatePortsVisibility(true);
    setShowPlus(true);
  };

  /**
   * 鼠标离开矩形主区域的时候隐藏连接桩和加号
   */
  const handleMainMouseLeave = () => {
    updatePortsVisibility(false);
    setShowPlus(false);
  };

  return (
    <div 
      className="flex items-center" 
      onMouseEnter={handleMainMouseEnter}
      onMouseLeave={handleMainMouseLeave}
    >
      <div
        className="flex items-center justify-between p-3 w-full h-12 bg-white 
             shadow-[0_-1px_4px_rgba(209,209,209,0.5),1px_1px_4px_rgba(217,217,217,0.5)] 
             rounded border transition-all duration-200
             border-transparent 
             hover:border-gray-200 
             hover:shadow-[0_-2px_4px_rgba(209,209,209,0.5),2px_2px_4px_rgba(217,217,217,0.5)]
             x6-selected:border-blue-500 
             x6-selected:shadow-[0_0_0_2px_rgba(52,113,249,0.2)]
             x6-selected:hover:border-blue-600"
      >
        <div className="flex items-center">
          {/* 节点类型icon */}
          <img
            src={NODE_TYPE_LOGO[data.value as NodeType] || "https://mdn.alipayobjects.com/huamei_f4t1bn/afts/img/A*EHqyQoDeBvIAAAAAAAAAAAAADtOHAQ/original"}
            alt={data.label}
            className="w-6 h-6"
          />

          <Tooltip title={data.label} mouseEnterDelay={0.8}>
            <div className="ml-2 text-sm text-gray-700 whitespace-nowrap overflow-hidden text-ellipsis flex-1">
              {data.label}
            </div>
          </Tooltip>
        </div>
         {/* 添加下游节点 */}
        {data.value !== NodeType.OUTPUT && (
          <>
            <div 
              className={`h-12 relative flex justify-center items-center x6-selected:visible
                     ${showPlus ? 'visible' : 'invisible'}`}>
              <div 
                className="cursor-pointer"
                onClick={handlePlusClick}
              >
                <PlusCircleOutlined
                  className={`w-4 h-4 text-blue-600 transition-all duration-200 `}
                />
              </div>
            </div>
            <NodeTypeSelector
              visible={plusActionSelected}
              position={menuPosition}
              context={{ source: node as Cell, target: null, edge: null }}
              onNodeTypeSelect={handleNodeTypeSelect}
              onClose={() => setPlusActionSelected(false)}
            />
          </>
        )}
      </div>
    </div>
  );
};

export default CustomNode;